package com.zem.imos.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zem.imos.Entity.*;
import com.zem.imos.Entity.Params.ParamsPatient;
import com.zem.imos.Entity.Params.ParamsRegister;
import com.zem.imos.Mapper.*;
import com.zem.imos.Util.JWT;
import com.zem.imos.Util.Validate;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RegisterMapper registerMapper;
    @Autowired
    DoctorMapper doctorMapper;
    @Autowired
    DrugsorderMapper drugsorderMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    SubdepartmentMapper subdepartmentMapper;

    /**
     * 用户登陆
     * @author ZEM
     * @Time 2021/11/23
     * @Description 用户登陆返回token  token 有效期30天
     */
    public RespEntity login(String username, String password)
    {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        ParamsPatient paramsPatient = patientMapper.selectOnePatient(queryWrapper);
        if(paramsPatient == null)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"密码或用户名错误"));
            return res;
        }
        if(paramsPatient.getRole()!= 1)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"请使用患者账号登陆"));
            return res;
        }
        if(DigestUtils.md5DigestAsHex(password.getBytes()).equals(paramsPatient.getPassword()))
        {
            JWT jwt = new JWT();
            String token = jwt.createJwtForPatient(paramsPatient,30*1000*60*60*24L);
            JSONObject object = new JSONObject();
            object.put("token",token);
//            object.put("user",user);
            RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"连接成功"),object);
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"密码或用户名错误"));
        return res;
    }

    /**
     * 患者账号注册
     * @author ZEM
     * @Time 2021/11/23
     * @Description 注册患者账号
     */
    public RespEntity logon(ParamsPatient paramsUser)
    {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",paramsUser.getUsername());
        if(!Validate.isPhoneLegal(paramsUser.getUsername()))
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"用户名请输入手机号"));
            return res;
        }
        if(patientMapper.selectOnePatient(queryWrapper)!= null)
        {
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"用户名已存在"));
            return res;
        }
        if (paramsUser.getPassword() != null)
            paramsUser.setPassword(DigestUtils.md5DigestAsHex(paramsUser.getPassword().getBytes()));
        User user = new User(paramsUser);
        Patient patient = new Patient(paramsUser);
        user.setRole(1);
        userMapper.insert(user);
        patient.setUserId(user.getId());
        patientMapper.insert(patient);
        RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"用户新增成功"));
        return res;

    }

    /**
     * 用户预约挂号
     * @author ZSQ
     * @Time 2021/11/30
     * @Description 通过用户id获取就诊的挂号单 （就诊单）的开药信息和就诊信息
     * 未测试
     */
     // 挂号
    public RespEntity register(HttpServletRequest request, ParamsRegister paramsRegister)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            User patient = userMapper.selectById((Long)claims.get("id"));
            User doctor = userMapper.selectById(paramsRegister.getDoctorId());
            if(patient == null || doctor ==null)
            {
                Register register = new Register(paramsRegister);
                long nowTime =System.currentTimeMillis();
                register.setTimestamp(nowTime);
                register.setStatus(0);
                register.setPatientId((Long)claims.get("userId"));
                registerMapper.insert(register);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"预约成功"),register);
                return res;

            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"医生用户名错误"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;

    }
    /**
     * 患者获取该患者所有的就诊济记录
     * @author ZEM
     * @Time 2021/11/30
     * @Description 根据患者id获取该患者的所有就诊记录（就诊时间、症状、诊断、给药情况）
     */
    public RespEntity getuservisit(HttpServletRequest request, Page page , Long userid)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            if(claims.get("role").equals("患者") )
            {
                QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("patient_id", userid);
                queryWrapper.ge("status", 1);
                IPage<List<Map>> user = userMapper.getuservisitbyuser(page, queryWrapper);
                Map<String,Object> Data = new HashMap();
                List <Map> records = new ArrayList<Map>();
                Data.put("total",user.getTotal());

                for(int i =0 ;i<user.getTotal();i++)
                {
                    int j ;
                    Map temp  = (Map) user.getRecords().get(i);
                    QueryWrapper<DrugsOrder> queryFordrugsorder = new QueryWrapper<>();
                    queryFordrugsorder.eq("register_id", temp.get("registerId"));
                    List<Map> drugsorders = drugsorderMapper.selectOrderList(queryFordrugsorder);
                    List drugsarray = new ArrayList();
                    for(j= 0;j<drugsorders.size();j++)
                        drugsarray.add((String)drugsorders.get(j).get("drug_name")+'*'+(String)drugsorders.get(j).get("drugs_order_num"));
                    temp.put("drugname", StringUtils.join(drugsarray.toArray(), ";"));
                    records.add(temp);
                }
                Data.put("records",records);
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"就诊患者信息查找成功"), Data);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"查无此患者"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }

    /**
     * 患者获取自身信息
     * @author ZEM
     * @Time 2021/11/30
     * @Description 患者获取自身信息
     */
    public RespEntity getuserinfo(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            Long id = (Long) claims.get("id");
            System.out.println(id); //test
            QueryWrapper<ParamsPatient> queryWrapper  = new QueryWrapper();
            queryWrapper.eq("user.id",id);
            ParamsPatient paramsPatient = patientMapper.selectOnePatient(queryWrapper);
            if(paramsPatient!=null)
            {
                RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"用户信息查找成功"), paramsPatient);
                return res;
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"查无此用户"));
            return res;
        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }

    /**
     * 获取医院的部门信息
     * @author ZEM
     * @Time 2021/11/30
     * @Description 获取医院的部门信息
     * 未测试
     */
    public RespEntity getdepartment(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        Claims claims = JWT.parseJwt(token);
        if(claims != null)
        {
            JSONArray resjson = new JSONArray();
            List<Department> department = departmentMapper.selectList(null);
            for(int i=0;i<department.size();i++)
            {
                JSONObject object = new JSONObject();
                object.put("value",department.get(i).getId());
                object.put("label",department.get(i).getDepartmentName());
                JSONArray children = new JSONArray();
                QueryWrapper<Subdepartment> queryWrapper = new QueryWrapper();
                queryWrapper.eq("parent_department_id", department.get(i).getId());
                List<Subdepartment> subdepartments = subdepartmentMapper.selectList(queryWrapper);
                for(int j=0;j<subdepartments.size();j++)
                {
                    JSONObject temp = new JSONObject();
                    temp.put("value",subdepartments.get(j).getId());
                    temp.put("label",subdepartments.get(j).getSubdepartmentName());
                    children.add(temp);
                }
                object.put("children",children);
                resjson.add(object);
            }
            RespEntity res = new RespEntity(new RespEntity.CRespCode(200,"用户信息查找成功"), resjson);
            return res;

        }
        RespEntity res = new RespEntity(new RespEntity.CRespCode(400,"获取用户token信息失败"));
        return res;
    }


}
